package com.hc.springbootredis.service.impl;

import com.hc.springbootredis.entity.Comment;
import com.hc.springbootredis.repository.CommentRepository;
import com.hc.springbootredis.service.CommentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.Optional;

//API方式操作缓存
@Service("CommentService2")
public class CommentServiceImpl2 implements CommentService {
    @Autowired
    CommentRepository commentRepository;

    @Autowired
    RedisTemplate redisTemplate;//简化Redis操作，封装了Jedis

    @Override
    public Comment findById(int id) {
        //指定缓存命名空间 comment:
        Object o = redisTemplate.opsForValue().get("comment:comment_" + id);
        if(o != null){
            return (Comment) o;
        }else {
            Optional<Comment> optional = commentRepository.findById(id);
            if(optional.isPresent()){
                Comment comment = optional.get();
                redisTemplate.opsForValue().set("comment:comment_" + id,comment);
                return comment;
            }
            return null;
        }
    }

    @Override
    public Comment updateComment(Comment comment) {
        commentRepository.updateComment(comment.getAuthor(), comment.getId());
        redisTemplate.opsForValue().set("comment:comment_" + comment.getId(),comment);
        return comment;
    }

    @Override
    public void deleteById(int id) {
        commentRepository.deleteById(id);
        redisTemplate.delete("comment:comment_" + id);
    }
}
